const db = require('../db/index')
const { date } = require('../uitls/dateFormat')

exports.addOrder = (req, res) => {
    let h = ''
    for (let index = 1; index < req.body.ids.length; index++) {
        h += '?,'
        if ((index + 1) == req.body.ids.length) {
            h += '?'
        }
    }
    h = req.body.ids.length == 1 ? '?' : h
    const sql = `select * from movieinfo where id in (${h})`
    db.query(sql, req.body.ids, (err, results) => {
        if (err) return res.cc(err)
        let values = []
        for (let index = 0; index < results.length; index++) {
            let arr = []
            arr.push(date(new Date()), results[index].id, req.user.phone, results[index].price, results[index].posters, results[index].name, results[index].category, results[index].Introduction)
            values.push(arr)
        }
        const sql = `insert into orders(addtime,idref,phone,price,imgUrl,movieTitle,category,content) values ?`
        db.query(sql, [values], function(err, results) {
            if (err) return res.cc(err)
            let del = 'delete from car where 1=1'
            db.query(del)
            res.send({
                status: 200,
                message: '成功'
            })
        })
    })
}

exports.getOrder = (req, res) => {
    const sql = `select * from orders where phone = ${req.user.phone}`
    db.query(sql, (err, results) => {
        if (err) return res.cc(err)
        res.send({
            status: 200,
            message: '获取用户订单成功！',
            data: results
        })
    })
}


//获取全部订单
exports.getOrderlist = (req, res) => {
    const sql = `select * from orders`
    db.query(sql, (err, results) => {
        if (err) return res.cc(err)
        res.send({
            status: 200,
            message: '获取用户订单成功！',
            data: results
        })
    })
}

//获取某个订单
exports.getByPhone = (req, res) => {
    const sql = `select * from orders where phone like '%${req.query.query}%'`
    db.query(sql, (err, results) => {
        if (err) return res.cc(err)
        res.send({
            status: 200,
            message: '获取用户订单成功！',
            data: results
        })
    })
}

//删除订单
exports.delOrder = (req, res) => {
    const sql = `delete from orders where id = ${req.params.id}`
    db.query(sql, function(err, results) {
        if (err) return res.cc(err)
        res.send({
            status: 200,
            message: "删除订单成功！",
        })
    })
}